import os
from flask import Flask, send_file, jsonify, render_template
from basic.config import GlobalInfo, GlobalCfg
from basic.workspace import Workspace
from basic.log import Log


class Website(object):
    def __init__(self, ip, port, modules):
        self.app = Flask(__name__)
        self.ip = ip
        self.port = port
        self.modules = modules
        self.modules_gate = []
        self.workspace = Workspace(None, 'website')
        self.runlog = Log(self.workspace.path)
        self.template_path = os.path.join(GlobalInfo.server_home, 'web', 'static')
        self.javascript_path = os.path.join(GlobalInfo.server_home, 'web', 'javascript')
        
        # 注册module的路由
        for m in modules:
            for r in m.routes:
                if r.desc is not None:
                    self.modules_gate.append({"url": r.url, "name": r.name, "desc": r.desc})
                    self.runlog.log(f'入口路由{r.name}  {r.url}  {str(r.methods)}')
                self.app.add_url_rule(r.url, endpoint=r.name, view_func=r.hook, methods=r.methods)
                self.runlog.log(f'添加路由{r.name}  {r.url}  {str(r.methods)}')
        
        # 网站基础页面
        self.app.add_url_rule('/', endpoint='homepage', view_func=self.homepage)
        self.runlog.log(f'添加网站主页路由 /')
        self.app.add_url_rule('/website_list_tools', endpoint='list_tools', view_func=self.list_tools)
        self.runlog.log(f'添加网站主页工具列表 /website_list_tools')
        self.app.errorhandler(404)(self.page_not_found)
        self.runlog.log(f'添加网站主页404页面')
        self.app.add_url_rule('/web/javascript/jquery-3.7.1.min.js', endpoint='jquery', view_func=self.send_jquery)
        self.runlog.log(f'添加网站jquery请求页')

    def homepage(self):
        return send_file(self.template('homepage.html'))
    
    def list_tools(self):
        return jsonify(self.modules_gate)
        
    def page_not_found(self, e):
        return send_file(self.template('404.html')), 404
    
    def send_jquery(self):
        return send_file(self.javascript('jquery-3.7.1.min.js'))

    def run(self):
        self.runlog.log(f'开始运行。。。')
        self.app.run(self.ip, self.port)

    def template(self, name):
        return os.path.join(self.template_path, name)

    def javascript(self, name):
        return os.path.join(self.javascript_path, name)

if __name__ == "__main__":
    Website('127.0.0.1', '9988', []).run()

